<template>
    <el-container>
        <el-main  style="display: flex; flex-direction: column; width: 100%; height: 100%;">
            <div id="map" class="map-container"></div>
            <div v-if="hoveredCylinder" class="tooltip" :style="{ left: tooltipX + 'px', top: tooltipY + 'px' }">
                经度：{{ hoveredLng.toFixed(4) }}<br>
                纬度：{{ hoveredLat.toFixed(4) }}
            </div>
        </el-main>
        <!--        <el-card-->
        <!--                style="width: 250px; flex-direction: column;display: flex; position: absolute; right: 0px;margin-top: 3%; margin-right: 3%;align-items: center;">-->
        <!--            <span>航迹点编辑</span>-->
        <!--            <el-select size="small" style="margin-top: 2px; width: 230px;" placeholder="选择航迹点" v-model="pointId">-->
        <!--                <el-option v-for="(item,index) in path" :label="index" :key="index" :value="index"></el-option>-->
        <!--            </el-select>-->

        <!--            <div style="width: 230px; margin-top: 2px;display: flex; flex-direction: row;justify-content: space-between;">-->
        <!--                <span style="font-size: 1.2ch;color: gray;">经度:{{pointData.longitude}}</span>-->
        <!--                <span style="font-size: 1.2ch;color: gray;">纬度:{{pointData.latitude}}</span>-->
        <!--            </div>-->
        <!--            <div-->
        <!--                    style="width: 230px; display: flex;flex-direction: row; margin-top: 2px;align-items: center;justify-content: space-between;">-->
        <!--                <span>高度:</span>-->
        <!--                <el-input size="small" style="width: 180px;" v-model="pointData.altitude"-->
        <!--                          :placeholder="pointData.altitude"></el-input>-->
        <!--            </div>-->
        <!--            <div-->
        <!--                    style="width: 230px; display: flex;flex-direction: row; margin-top: 2px;align-items: center;justify-content: space-between;">-->
        <!--                <span>速度:</span>-->
        <!--                <el-input size="small" style="width: 180px;" v-model="pointData.speed"-->
        <!--                          :placeholder="pointData.speed"></el-input>-->
        <!--            </div>-->
        <!--            <div>-->

        <!--            </div>-->
        <!--            <el-select size="small" style="width: 230px; margin-top: 2px;" v-model="pointData.type"-->
        <!--                       placeholder="航迹点类型">-->
        <!--                <el-option label="过路点" value=1></el-option>-->
        <!--                <el-option label="悬停点" value=2></el-option>-->
        <!--                <el-option label="降落点" value=3></el-option>-->
        <!--            </el-select>-->
        <!--            <div style="display: flex;flex-direction: row;justify-content: space-around;">-->
        <!--                <el-button type="success" size="mini" style=" margin-top: 2px;" @click="editPoint()">确认</el-button>-->
        <!--            </div>-->
        <!--        </el-card>-->

        <el-footer>
            <div class="rBottom">
                <div>
                    <el-button @click="createAndClearRoute()" size="small" type="primary"
                               :disabled="controlButtonDisable">{{controlButton}}
                    </el-button>

                    <el-button @click="detailEdit()" v-show="detailEditButtonDisable" size="small"
                               type="primary">{{detailEditButton}}
                    </el-button>

                    <el-button @click="editForbidden()" size="small"
                               type="primary">{{forbiddenAction}}
                    </el-button>

                </div>
                <div>
                    <el-input size="small" style="width: 150px" placeholder="输入航线名称"
                              v-model="routeInfo.routeName"></el-input>
                    <el-select size="small" style="width: 150px; margin-left: 20px;" v-model="routeInfo.routeType"
                               placeholder="航线类型">
                        <el-option label="多旋翼" value=1></el-option>
                        <el-option label="固定翼" value=2></el-option>
                    </el-select>
                    <el-button @click="uploadRoute()" size="small" style="margin-left: 20px;"
                               type="success">上传航线
                    </el-button>
                </div>
            </div>

        </el-footer>
    </el-container>
</template>

<script>
    import mapboxgl from 'mapbox-gl';
    import * as THREE from 'three';
    import {GET_MAPBOX_MAP} from "../components/map/CreateMap";


    export default {
        data() {
            return {
                Rmap: null,
                scene: null,
                camera: null,
                renderer: null,
                cylinders: [],
                raycaster: new THREE.Raycaster(),
                mouse: new THREE.Vector2(),
                hoveredCylinder: null,
                tooltipX: 0,
                tooltipY: 0
            };
        },

        mounted() {
            this.initMap();
        },

        methods: {
            initMap() {
                const map = GET_MAPBOX_MAP();
                // this.map = GET_MAPBOX_MAP();
                map.on('style.load', () => {
                    // Insert the layer beneath any symbol layer.
                    const layers = map.getStyle().layers;
                    const labelLayerId = layers.find(
                        (layer) => layer.type === 'symbol' && layer.layout['text-field']
                    ).id;

                    map.addLayer(
                        {
                            'id': 'add-3d-buildings',
                            'source': 'composite',
                            'source-layer': 'building',
                            'filter': ['==', 'extrude', 'true'],
                            'type': 'fill-extrusion',
                            'minzoom': 15,
                            'paint': {
                                'fill-extrusion-color': '#aaa',

                                // Use an 'interpolate' expression to
                                // add a smooth transition effect to
                                // the buildings as the user zooms in.
                                'fill-extrusion-height': [
                                    'interpolate',
                                    ['linear'],
                                    ['zoom'],
                                    15,
                                    0,
                                    15.05,
                                    ['get', 'height']
                                ],
                                'fill-extrusion-base': [
                                    'interpolate',
                                    ['linear'],
                                    ['zoom'],
                                    15,
                                    0,
                                    15.05,
                                    ['get', 'min_height']
                                ],
                                'fill-extrusion-opacity': 0.6
                            }
                        },
                        labelLayerId
                    );
                });
                // this.map.on('load', () => this.setupThreeLayer());
                map.addControl(new mapboxgl.ScaleControl(), 'bottom-left')
                this.Rmap = map;
            },

            setupThreeLayer() {
                const customLayer = {
                    id: 'three-layer',
                    type: 'custom',
                    renderingMode: '3d',

                    onAdd: (map, gl) => {
                        this.scene = new THREE.Scene();
                        this.camera = new THREE.PerspectiveCamera();
                        this.renderer = new THREE.WebGLRenderer({
                            canvas: map.getCanvas(),
                            context: gl,
                            antialias: true
                        });

                        this.addEventListeners();
                    },

                    render: (gl, matrix) => {
                        this.updateCamera(matrix);
                        this.renderer.render(this.scene, this.camera);
                        this.map.triggerRepaint();
                    }
                };

                this.map.addLayer(customLayer, 'waterway-label');
            },

            addEventListeners() {
                // 左键添加圆柱
                this.map.on('click', e => this.createCylinder(e.lngLat));

                // 右键删除
                this.map.on('contextmenu', e => {
                    e.preventDefault();
                    this.deleteCylinder(e.point);
                });

                // 悬停检测
                this.map.on('mousemove', e => this.detectHover(e.point));
            },

            createCylinder(lngLat) {
                const position = this.lngLatToWorld(lngLat);
                const geometry = new THREE.CylinderGeometry(5, 5, 20, 32);
                const material = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
                const cylinder = new THREE.Mesh(geometry, material);

                cylinder.position.set(position.x, position.y, 10);
                cylinder.userData = { lngLat };
                this.scene.add(cylinder);
                this.cylinders.push(cylinder);
            },

            deleteCylinder(screenPoint) {
                this.updateRaycaster(screenPoint);
                const intersects = this.raycaster.intersectObjects(this.cylinders);

                if (intersects.length > 0) {
                    const obj = intersects.object;
                    this.scene.remove(obj);
                    this.cylinders = this.cylinders.filter(c => c !== obj);
                }
            },

            detectHover(screenPoint) {
                this.updateRaycaster(screenPoint);
                const intersects = this.raycaster.intersectObjects(this.cylinders);

                if (intersects.length > 0) {
                    this.hoveredCylinder = intersects.object;
                    [this.tooltipX, this.tooltipY] = [screenPoint.x, screenPoint.y];
                    this.map.getCanvas().style.cursor = 'pointer';
                } else {
                    this.hoveredCylinder = null;
                    this.map.getCanvas().style.cursor = '';
                }
            },

            updateCamera(matrix) {
                const m = new THREE.Matrix4().fromArray(matrix);
                this.camera.projectionMatrix = m;
            },

            lngLatToWorld(lngLat) {
                return this.map.project(lngLat);
            },

            updateRaycaster({ x, y }) {
                const rect = this.map.getCanvas().getBoundingClientRect();
                this.mouse.x = ((x - rect.left) / rect.width) * 2 - 1;
                this.mouse.y = -((y - rect.top) / rect.height) * 2 + 1;
                this.raycaster.setFromCamera(this.mouse, this.camera);
            }
        },

        computed: {
            hoveredLng() {
                if (this.hoveredCylinder) {
                    return this.hoveredCylinder.userData.lngLat.lng;
                }
                return 0;
            },
            hoveredLat() {
                if (this.hoveredCylinder) {
                    return this.hoveredCylinder.userData.lngLat.lat;
                }
                return 0;
            }
        }
    };
</script>

<style>
    .map-container {
        width: 100vw;
        height: 100vh;
    }

    .mapClass {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
    }
    .tooltip {
        position: fixed;
        background: white;
        padding: 8px;
        border: 1px solid #ccc;
        pointer-events: none;
    }
</style>
